import {
  reqUpload
} from '@/api/common'
import {
  reqUpdateUserInfo
} from '@/api/user'
import userStore from '@/store/userStore'
import {
  toast
} from '@/utils/extendApi'
import {
  setStorage
} from '@/utils/storage'
import {
  ComponentWithStore
} from 'mobx-miniprogram-bindings'

ComponentWithStore({

  data: {
    defaultAvatar: "https://yi-ban-jia.oss-cn-beijing.aliyuncs.com/default.png",
    avatar: '',
    nickname: ''
  },

  storeBindings: {
    store: userStore,
    fields: ['userInfo'],
    actions: ['setUserInfo']
  },
  methods: {
    back() {
      wx.navigateBack()
    },
    async chooseavatar(event) {
      const res = await reqUpload(event.detail.avatarUrl, "file")
      this.setData({
        avatar: res.data
      })
    },
    async save() {
      this.data.userInfo.avatar = this.data.avatar
      this.data.userInfo.nickname = this.data.nickname
      // 修改数据库中的用户信息
      await reqUpdateUserInfo(this.data.userInfo)
      toast({
        title: '修改成功'
      })
      // 修改内存中的用户信息
      this.setUserInfo(this.data.userInfo)
      // 修改本地持久化的用户信息
      setStorage('userInfo', this.data.userInfo)
    }
  },
  lifetimes: {
    attached() {
      this.setData({
        avatar: this.data.userInfo.avatar,
        nickname: this.data.userInfo.nickname
      })
    }
  }
})